package com.mega.common.redis.utils;

import cn.hutool.core.date.format.FastDateFormat;
import com.baomidou.mybatisplus.annotation.TableName;
import com.mega.common.core.constant.CacheConstants;
import com.mega.common.core.enums.CommonMsgEnum;
import com.mega.common.core.exception.BusinessException;
import com.mega.common.core.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.Optional;

@Slf4j
public class CodeUtils {

    /**
     * 标准日期格式：yyyyMMdd
     */
    public final static String PURE_DATE_PART = "yyyyMMdd";
    /**
     * 标准日期格式 {@link FastDateFormat}：yyMMdd
     */
    public final static FastDateFormat PURE_DATE_FORMAT = FastDateFormat.getInstance(PURE_DATE_PART);
    /**
     * stringRedisTemplate
     */
    private static final StringRedisTemplate stringRedisTemplate = SpringUtils.getBean(StringRedisTemplate.class);

    /**
     * 根据实体注解获取表名
     *
     * @param obj
     * @return
     */
    public static String getTableName(Object obj) {
        return Optional.ofNullable(obj.getClass().getAnnotation(TableName.class).value()).
                orElseThrow(() -> new BusinessException(CommonMsgEnum.CREATE_CODE_ERROR));
    }

    /**
     * @description: 编号枚举
     * @author Eric
     * @date 2020/09/24 14:07
     */
    public static String getDateCode(Object obj) {
        String key = CacheConstants.TABLE_CODE + getTableName(obj);
        String today = PURE_DATE_FORMAT.format(new Date());
        String value = today + "0001";
        //从redis中获取ID
        if (!stringRedisTemplate.hasKey(key)) {
            stringRedisTemplate.opsForValue().set(key, value);
            return value;
        } else {
            String taskId = stringRedisTemplate.opsForValue().get(key);
            if (today.equals(taskId.substring(0, 8))) {
                stringRedisTemplate.opsForValue().increment(key, 1);
                value = stringRedisTemplate.opsForValue().get(key);
                return value;
            } else {
                stringRedisTemplate.opsForValue().set(key, value);
                return value;
            }
        }
    }

    public static String incr(String key, String strFormat) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, stringRedisTemplate.getConnectionFactory());
        Long increment = entityIdCounter.addAndGet((long) 1);

        //位数不够，前面补0
        DecimalFormat df = new DecimalFormat(strFormat);
        return df.format(increment);
    }
}
